import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../provider/AuthProvider.dart';
import '../utils/api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _phoneController = TextEditingController();
  final _pwdController = TextEditingController();
  bool _loading = false;

  void _showMsg(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
  }

  Future<bool> checkUserExists(String phone) async {
    try {
      final res = await Api.get('/user/exists', params: {'phone': phone});
      // 接口返回 { code: 0, data: true/false, msg: '...' }
      return res['code'] == 0 && res['data'] == true;
    } catch (e) {
      _showMsg('检查用户状态失败');
      return false;
    }
  }

  Future<bool> registerUser(String phone, String pwd) async {
    try {
      final res = await Api.post(
        '/user/register',
        body: {'username': phone, 'password': pwd, 'nickname': phone},
      );
      if (res['code'] == 0) {
        _showMsg('注册成功');
        return true;
      } else if (res['msg'] == '用户名已存在') {
        // 用户已存在，改成直接登录
        _showMsg('用户已存在，正在登录...');
        return await loginUser(phone, pwd); // 自动登录，返回登录结果
      } else {
        _showMsg(res['msg'] ?? '注册失败');
        return false;
      }
    } catch (e) {
      _showMsg('注册接口异常');
      return false;
    }
  }

  Future<bool> loginUser(String phone, String pwd) async {
    try {
      final res = await Api.post(
        '/user/login',
        body: {'username': phone, 'password': pwd},
      );
      if (res['code'] == 0) {
        final token = res['data']['token'];
        final userId = res['data']['user']["id"];

        // 存本地
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString('token', token);

        // 通知 Provider 更新登录状态
        final authProvider = Provider.of<AuthProvider>(context, listen: false);
        await authProvider.login(token, userId.toString());

        return true;
      } else {
        _showMsg(res['msg'] ?? '登录失败');
        return false;
      }
    } catch (e) {
      _showMsg('登录接口异常');
      return false;
    }
  }

  void _handleLogin() async {
    final phone = _phoneController.text.trim();
    final pwd = _pwdController.text;

    if (phone.isEmpty || pwd.isEmpty) {
      _showMsg("手机号或密码不能为空");
      return;
    }

    setState(() => _loading = true);

    try {
      bool exists = await checkUserExists(phone);

      if (!exists) {
        bool regOk = await registerUser(phone, pwd);
        if (!regOk) {
          setState(() => _loading = false);
          return;
        }
      } else {
        // 用户已存在，直接登录
        bool loginOk = await loginUser(phone, pwd);
        if (!loginOk) {
          setState(() => _loading = false);
          return;
        }
      }

      // 登录成功后，路由会自动跳转，无需额外操作
    } catch (e) {
      _showMsg("网络异常，请稍后重试");
    } finally {
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 32),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const FlutterLogo(size: 72),
              const SizedBox(height: 32),
              TextField(
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: '手机号',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _pwdController,
                obscureText: true,
                decoration: InputDecoration(
                  labelText: '密码',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                height: 48,
                child: ElevatedButton(
                  onPressed: _loading ? null : _handleLogin,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.black,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: _loading
                      ? const CircularProgressIndicator(color: Colors.white)
                      : const Text(
                          "登录 / 注册",
                          style: TextStyle(color: Colors.white),
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
